package com.itheima.service.impl;

import cn.hutool.core.util.IdUtil;
import com.itheima.dto.ShoppingCartDto;
import com.itheima.dto.SubShoppingCartDto;
import com.itheima.mapper.ShoppingCartMapper;
import com.itheima.pojo.ShoppingCart;
import com.itheima.service.ShoppingCartService;
import com.itheima.thread.TokenThreadUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author YangJiaHao
 */
@Service
public class ShoppingCartServiceImpl implements ShoppingCartService {
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;



    @Override
    public Boolean add(ShoppingCartDto shoppingCartDto) {
        ShoppingCart shoppingCart = shoppingCartMapper.selectShoppingCartById(shoppingCartDto.getDishId(),shoppingCartDto.getSetmealId());
        if (shoppingCart!=null){
            Integer number = shoppingCart.getNumber()+1;
            Integer updateResult = shoppingCartMapper.updateNumberById(shoppingCart.getId(),number);
            if (updateResult!=1){
                throw new RuntimeException("添加失败");
            }else {
                return updateResult==1;
            }
        }
        ShoppingCart newShoppingCart = new ShoppingCart();
        BeanUtils.copyProperties(shoppingCartDto, newShoppingCart);
        newShoppingCart.setId(IdUtil.getSnowflakeNextIdStr());
        newShoppingCart.setUserId(TokenThreadUtils.getThreadLocal().getId());
        newShoppingCart.setNumber(1);
        Integer res = shoppingCartMapper.insertShoppingCart(newShoppingCart);

        return res==1;
    }

    @Override
    public List<ShoppingCart> list() {
        return shoppingCartMapper.selectAll();
    }

    @Override
    public Boolean clean() {
        Integer res = shoppingCartMapper.deleteAll(TokenThreadUtils.getThreadLocal().getId());
        return res>0;
    }

    @Override
    public Boolean remove(SubShoppingCartDto dto) {
        ShoppingCart shoppingCart = shoppingCartMapper.selectShoppingCartByDto(dto);
        if (shoppingCart.getNumber()>1){
            Integer number = shoppingCart.getNumber()-1;
            Integer result = shoppingCartMapper.updateNumberByDto(dto,number);
            return result==1;
        }
        Integer res = shoppingCartMapper.deleteById(dto);
        return res>0;
    }
}
